<?php
require 'config.php';
function getDistance($lat1, $lng1, $lat2, $lng2, $len_type = 1, $decimal = 2)
{
    $lo = gcjBd($lat2, $lng2);
    $lat2 = $lo['lat'];
    $lng2 = $lo['lng'];
    $EARTH_RADIUS = 6378.137;
    $PI = 3.1415926;
    $radLat1 = $lat1 * $PI / 180.0;
    $radLat2 = $lat2 * $PI / 180.0;
    $a = $radLat1 - $radLat2;
    $b = ($lng1 * $PI / 180.0) - ($lng2 * $PI / 180.0);
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
    $s = $s * $EARTH_RADIUS;
    $s = round($s * 1000);
    if ($len_type > 1) {
        $s /= 1000;
    }
    return round($s, $decimal);
}

date_default_timezone_set('PRC');
$user_id = $_REQUEST['user_id'];
$shopId = $_REQUEST['shopId'];
$json = $_REQUEST['json'];
$buycar = $_REQUEST['buycar'];

//file_put_contents("tsxx.txt", "\r\n".$user_id."\r\n", FILE_APPEND);
// file_put_contents("tsxx.txt", "\r\n---------店铺下单开始".date('Y-m-d H:i:s')."--------\r\n", FILE_APPEND);
// file_put_contents("tsxx.txt", "\r\n收到user_id:".$user_id."\r\n", FILE_APPEND);
// file_put_contents("tsxx.txt", "\r\n收到shopId:".$shopId."\r\n", FILE_APPEND);
// file_put_contents("tsxx.txt", "\r\n收到转换前json:".$json."\r\n", FILE_APPEND);
// file_put_contents("tsxx.txt", "\r\n收到转换前buycar:".$buycar."\r\n", FILE_APPEND);
$json = json_decode($json, true);
$buycar = json_decode($buycar, true);

// file_put_contents('xiadan.txt',var_export($buycar,true));
// file_put_contents('xiadan2.txt',var_export($json,true));
// file_put_contents('xiadan3.txt',var_export($_REQUEST,true));

if (isset($json[0]['address_id'])) {
    $json[1]['address_id'] = $json[0]['address_id'];
}

if (!isset($json[0]['shops_liuyan'])) {
    $json[0]['shops_liuyan'] = "";
}

if (!isset($json[0]['hxiaoji'])) {
    $json[0]['hxiaoji'] = $json[0]['yxiaoji'];
}

if (!isset($json[0]['shops_youhui'])) {
    $json[0]['shops_youhui'] = 0;
}

if (!isset($json[0]['ps_time'])) {
    $json[0]['ps_time'] = '立即送出';
}

// file_put_contents("tsxx.txt", "\r\n收到转换后json:".json_encode($json)."\r\n", FILE_APPEND);
// file_put_contents("tsxx.txt", "\r\n收到转换后buycar:".json_encode($buycar)."\r\n", FILE_APPEND);
// file_put_contents("tsxx.txt", "\r\n---------店铺下单结束--------\r\n", FILE_APPEND);

$t = 0;
/*******获取该店铺的商品id及数量等重要信息***********/
for ($i = 0; $i < count($buycar); $i++) {
    if (isset($buycar[$i]['goods_shopId'])) {
        if ($buycar[$i]['goods_shopId'] == $shopId) {
            $cart[$t]['goods_id'] = $buycar[$i]['goods_id'];
            $cart[$t]['goods_num'] = $buycar[$i]['goods_num'];
            $cart[$t]['shuxing_id'] = $buycar[$i]['shuxing_id'];
            $cart[$t]['shuxing_title'] = $buycar[$i]['shuxing_title'];
            $t++;
        }
    }
}
/**********获取店铺基本信息***********/
$sql = "SELECT * FROM " . $oto . "_shops where shopId='{$shopId}' LIMIT 1";
$result = $db->query($sql);
while ($row = $result->fetch_assoc()) {
    $shop_info[] = $row; //将取得的所有数据赋值给person_info数组
}

/**********获取该店铺商品生成订单所需信息***********/
for ($i = 0; $i < count($cart); $i++) {
    $lin_goods_id = $cart[$i]['goods_id'];
    $sql = "SELECT * FROM " . $oto . "_goods where goodsId='{$lin_goods_id}' LIMIT 1";
    $result = $db->query($sql);
    while ($row = $result->fetch_assoc()) {
        $goods_info[$i][] = $row; //将取得的所有数据赋值给person_info数组
    }
    if (isset($goods_info[$i])) {
        $cart[$i]['goodsImg'] = $goods_info[$i][0]['goodsImg'];
        $cart[$i]['goodsStock'] = $goods_info[$i][0]['goodsStock'];
        $cart[$i]['goodsName'] = $goods_info[$i][0]['goodsName'];
        $cart[$i]['shopPrice'] = $goods_info[$i][0]['shopPrice'];
        $cart[$i]['goodsProportion'] = $goods_info[$i][0]['goodsProportion']; //商品分佣比例
    }
    //file_put_contents("tsxx.txt", "\r\n".$cart[$i]['shuxing_id']."\r\n", FILE_APPEND);
    $attr_id = $cart[$i]['shuxing_id'];
    if ($attr_id == 0) {
        $cart[$i]['shuxing_money'] = 0;
        $cart[$i]['goods_attr'] = '';
        $cart[$i]['goodss_attr_id2'] = '';
    } else {
        $attr_id = explode(",", $attr_id);
        $goods_attr = '';
        $money = 0;
        for ($j = 0; $j < count($attr_id); $j++) {
            $z_attr_id = $attr_id[$j];
            $sql = "SELECT * FROM " . $oto . "_goods_attributes," . $oto . "_attributes where id='$z_attr_id' and " . $oto . "_goods_attributes.attrId=" . $oto . "_attributes.attrId";
            $result = $db->query($sql);
            while ($row = $result->fetch_assoc()) {
                $z_attr_money[$j] = $row; //将取得的所有数据赋值给person_info数组
            }
            $money += $z_attr_money[$j]['attrPrice'];
            if ($j == 0) {
                $goods_attr .= $z_attr_money[$j]['attrName'] . ":" . $z_attr_money[$j]['attrVal'];
            } else {
                $goods_attr .= ',' . $z_attr_money[$j]['attrName'] . ":" . $z_attr_money[$j]['attrVal'];
            }

            if ($z_attr_money[$j]['attrStock'] < $cart[$i]['goodsStock']) {
                $cart[$i]['goodsStock'] = $z_attr_money[$j]['attrStock'];
            }

        }
        $cart[$i]['shuxing_money'] = $money; //属性价钱
        $cart[$i]['goods_attr'] = $goods_attr; //属性名字集合
        $cart[$i]['goodss_attr_id2'] = $cart[$i]['shuxing_id'];
    }
}
/***上面获取购物车内基本信息**/
/***下面开始验证购物车数据以及库存配送范围等信息***/
//获取选择的收货地址
$address_id = $json[1]['address_id'];
$sql = "select * from `" . $oto . "_user_address` where `userId`='" . $user_id . "' and `addressId`='{$address_id}'";
$result = $db->query($sql);
while ($row = $result->fetch_assoc()) {
    $user_address[] = $row; //将取得的所有数据赋值给person_info数组
}
//验证
$max = count($cart);
$pan = 0;
// $shop_id = $shopId;
// $ad1 = $user_address[0]['areaId1'];
// $ad2 = $user_address[0]['areaId2'];
// $ad3 = $user_address[0]['areaId3'];
// $ad4 = $user_address[0]['communityId'];
// $sql = "select * from `" . $oto . "_shops_communitys` where `shopId`='" . $shop_id . "' and areaId1='{$ad1}' and areaId2='{$ad2}' and areaId3='{$ad3}' and communityId='{$ad4}'";
// $result = $db->query($sql);
// while ($row = $result->fetch_assoc()) {
//     $isPs[$i] = $row; //将取得的所有数据赋值给person_info数组
// }

$lat = $user_address[0]['lat'];
$lon = $user_address[0]['lng'];

if ($shop_info[0]['deliveryType'] == 1) {
    $ptm = getPtDeliveryConfig();
    if ($shop_info[0]['deliveryType'] == 1 && !empty($ptm)) {
        $lat2 = $shop_info[0]['latitude'];
        $lon2 = $shop_info[0]['longitude'];
        $shop_info[0]['juli'] = getDistance($lat, $lon, $lat2, $lon2);

        if ($shop_info[0]['juli']) {
            for ($j = 0; $j < count($ptm); $j++) {
                if ($shop_info[0]['juli'] <= $ptm[$j]['go_distance'] * 1000) {
                    $json[0]['ps_time'] = "预计到达时间(" . (date("H:i", time() + $ptm[$j]['go_distance_time'] * 60)) . ")";
                    $shop_info[0]['deliveryMoney'] = $ptm[$j]['go_money'];
                    break;
                }
                if ($j == count($ptm) - 1 && $shop_info[0]['juli'] > $ptm[$j]['go_distance'] * 1000) {
                    $pan = 1;
                    $data[0]['pan'] = 1;
                    $data[0]['msg'] = "不支持该配送地址";
                }
            }
        }
    }
}

if ($pan == 1) {
    //file_put_contents("tsxx.txt", "\r\n".json_encode($data)."\r\n", FILE_APPEND);
    echo json_encode($data);
    die();
} else {
    $data[0]['pan'] = 0;
    $data[0]['msg'] = $cart[$i]['goodsName'] . "可配送该地址";
}
for ($i = 0; $i < $max; $i++) {
    if ($cart[$i]['goodsStock'] < $cart[$i]['goods_num']) {
        $pan = 1;
        $data[$i]['pan'] = 1;
        $data[$i]['msg'] = $cart[$i]['goodsName'] . "不能大于" . $cart[$i]['goodsStock'] . "件";
    } else {
        $data[$i]['pan'] = 0;
        $data[$i]['msg'] = $cart[$i]['goodsName'] . "库存充足可购买";
    }
}
/*优惠券验证是否过期*/
// $time=time();
// $sql="select * from `".$oto."_youhui_user_link`,`".$oto."_youhui` where ".$oto."_youhui_user_link.user_id='{$user_id}' and u_is_effect='1' and ".$oto."_youhui_user_link.youhui_id=".$oto."_youhui.id";
// file_put_contents("tsxx.txt", "\r\n".$sql."\r\n", FILE_APPEND);
// $result=$db->query($sql);
// while($row=$result->fetch_assoc()){
//     $yhq_info[]=$row;//将取得的所有数据赋值给person_info数组
// }
// for($i=0;$i<count($yhq_info);$i++)
// {
//     if($yhq_info[$i]['end_time']<$time)
//     {
//         $youhui_id=$yhq_info[$i]['youhui_id'];
//         $sql="update ".$oto."_youhui_user_link set u_is_effect='0' where user_id='{$user_id}' and youhui_id='{$youhui_id}'";
//         $result=$db->query($sql);
//     }
// }
// for($i=0;$i<count($json);$i++)
// {
//     $order_id=$json[$i]['orderId'];
//     $sql="select * from `".$oto."_orders` where `orderId`='".$order_id."'";
//     $result=$db->query($sql);
//     while($row=$result->fetch_assoc()){
//         $order_youhui_info[$i]=$row;//将取得的所有数据赋值给person_info数组
//     }
//     $order_youhui_id=$order_youhui_info[$i]['couponId'];
//     $sql="select * from `".$oto."_youhui_user_link` where `user_id`='{$user_id}' and youhui_id='{$order_youhui_id}' and u_is_effect='1'";
//     $result=$db->query($sql);
//     while($row=$result->fetch_assoc()){
//         $yhq_yz[]=$row;//将取得的所有数据赋值给person_info数组
//     }
//     if(!isset($yhq_yz) && $order_youhui_id!=0 && $order_youhui_id!='0')
//     {
//         $data[0]['pan']=-2;
//         $data[0]['msg']='优惠券已过期或不存在';
//         echo json_encode($data);
//         exit();
//     }
//     else
//     {
//         if($order_youhui_id==0 || $order_youhui_id=='0');
//         else if($yhq_yz[0]['surplus']<1)
//         {
//             $data[0]['pan']=-2;
//             $data[0]['msg']='优惠券已过期或不存在';
//             echo json_encode($data);
//             exit();
//         }
//     }
// }
/*优惠券验证end*/
if ($pan == 1) {
    //file_put_contents("tsxx.txt", "\r\n".json_encode($data)."\r\n", FILE_APPEND);
    echo json_encode($data);
    die();
}
$y = date("Y", time());
$m = date("m", time());
$d = date("d", time());
$serviceStartTime = $shop_info[0]['serviceStartTime'];
$serviceEndTime = $shop_info[0]['serviceEndTime'];
$serviceStartTime_fen = explode('.', $serviceStartTime);
$serviceEndTime_fen = explode('.', $serviceEndTime);
$start_time = mktime($serviceStartTime, $serviceStartTime_fen[1], 0, $m, $d, $y);
$end_time = mktime($serviceEndTime, $serviceEndTime_fen[1], 0, $m, $d, $y);
$time3 = time();
if ($time3 < $start_time || $time3 > $end_time) {
    $pan = 1;
    $data[0]['pan'] = 1;
    $data[0]['msg'] = "商家休息中";
}
if ($pan == 1) {
    //file_put_contents("tsxx.txt", "\r\n".json_encode($data)."\r\n", FILE_APPEND);
    echo json_encode($data);
    die();
}
/**********************************************************/
for ($i = 0; $i < 1; $i++) {
    // $dizhi = '';
    // $sql = "select * from `" . $oto . "_areas` where `areaId`='" . $user_address[$i]['areaId1'] . "'";
    // $result = $db->query($sql);
    // while ($row = $result->fetch_assoc()) {
    //     $sheng[$i] = $row; //将取得的所有数据赋值给person_info数组
    // }
    // $sql = "select * from `" . $oto . "_areas` where `areaId`='" . $user_address[$i]['areaId2'] . "'";
    // $result = $db->query($sql);
    // while ($row = $result->fetch_assoc()) {
    //     $shi[$i] = $row; //将取得的所有数据赋值给person_info数组
    // }
    // $sql = "select * from `" . $oto . "_areas` where `areaId`='" . $user_address[$i]['areaId3'] . "'";
    // $result = $db->query($sql);
    // while ($row = $result->fetch_assoc()) {
    //     $xian[$i] = $row; //将取得的所有数据赋值给person_info数组
    // }
    // $sql="select * from `".$oto."_communitys` where `communityId`='".$user_address[$i]['communityId']."'";
    // $result=$db->query($sql);
    // while($row=$result->fetch_assoc()){
    //     $jiedao[$i]=$row;//将取得的所有数据赋值给person_info数组
    // }
    // $dizhi = $sheng[$i]['areaName'] . $shi[$i]['areaName'] . $xian[$i]['areaName'] . $user_address[$i]['address'];
    $dizhi = $user_address[$i]['address']." ".$user_address[$i]["number"];
}
/*********************************************/
$orderunique = floor(microtime(true) * 1000); //是否同一批下单
$createTime = date('Y-m-d H:i:s'); //下单时间
$areaId1 = $user_address[0]['areaId1']; //省
$areaId2 = $user_address[0]['areaId2']; //市
$areaId3 = $user_address[0]['areaId3']; //区
$communityId = 0; //社区id
$userAddress = $dizhi; //配送详细地址
$userId = $user_id; //用户id
$userName = $user_address[0]['userName']; //收货人名字
$userPhone = $user_address[0]['userPhone']; //收货人手机号
for ($i = 0; $i < 1; $i++) //添加直购商品订单
{
    $orderStrNo = microtime(true);
    //$orderStrNo=time();
    $sql = "INSERT INTO " . $oto . "_orderids (`rnd`) VALUES ('{$orderStrNo}')";
    $result = $db->query($sql);
    //$sql="SELECT * FROM ".$oto."_orderids where rnd='{$orderStrNo}'";
    $sql = "SELECT * FROM " . $oto . "_orderids order by id DESC";
    $result = $db->query($sql);
    while ($row = $result->fetch_assoc()) {
        $orderids_info[] = $row; //将取得的所有数据赋值给person_info数组
    }
    $orderNo = $orderids_info[0]['id'] . "" . (fmod($orderids_info[0]['id'], 7)); //订单号
    $orderStatus = '-2'; //订单状态
    $totalMoney = 0; //总消费
    $deliverType = $shop_info[0]["deliveryType"]; //配送方式
    $orderScore = 0; //获得积分
    $orderRemarks = $json[$i]['shops_liuyan']; //买家留言
    $requireTime = $json[$i]['ps_time']; //期望送达时间
    $needPay = 0; //应付金额
    $youhui_money = 0; //优惠价格
    $youhui_id = '';
    $isSelf = $json[$i]['shops_psway'];
    $sql = "INSERT INTO " . $oto . "_orders (`orderNo`,`areaId1`,`areaId2`,`areaId3`,`shopId`,`orderStatus`,`totalMoney`,`deliverType`,`userId`,`userName`,`communityId`,`userAddress`,`userPhone`,`orderScore`,`orderRemarks`,`createTime`,`orderunique`,`needPay`,`orderType`,`payType`,`isPay`,`isSelf`,`requireTime`,`lng`,`lat`) VALUES ('$orderNo','$areaId1','$areaId2','$areaId3','$shopId','$orderStatus','$totalMoney','$deliverType','$userId','$userName','$communityId','$userAddress','$userPhone','$orderScore','$orderRemarks','$createTime','$orderunique','$needPay','1','1','0','$isSelf','$requireTime','$lon','$lat')";
    $result = $db->query($sql); //插入order表
    file_put_contents("tsxx.txt", "\r\n" . $sql . "执行：" . $result . "\r\n", FILE_APPEND);
    $sql = "select * from `" . $oto . "_orders` where `orderNo`='" . $orderNo . "' and `userId`='{$userId}' and `orderunique`='{$orderunique}'";
    $result = $db->query($sql); //查询刚插进去的orderId
    while ($row = $result->fetch_assoc()) {
        $order[0] = $row; //将取得的所有数据赋值给person_info数组
    }
    //file_put_contents("tsxx.txt", "\r\n".$sql."执行：\r\n", FILE_APPEND);
    $z_money = 0;
    $yongjin = 0;
    for ($j = 0; $j < count($cart); $j++) {
        //if($cart[$j]['shopId']==$shopId)
        //{
        $orderId = $order[0]['orderId'];
        $data[0]['orderId'] = $orderId;
        $sql = "INSERT INTO " . $oto . "_order_reminds (`orderId`,`userId`,`shopId`,`createTime`) VALUES ('$orderId','$userId','$shopId','$createTime')";
        $result = $db->query($sql); //插入order_reminds表
        $t++;
        $goodsId = $cart[$j]['goods_id'];
        $goodsNums = $cart[$j]['goods_num'];
        $goodsPrice = $cart[$j]['shopPrice'] + $cart[$j]['shuxing_money'];
        $goodsAttrId = $cart[$j]['goodss_attr_id2'];
        $goodsAttrName = $cart[$j]['goods_attr'];
        $goodsName = $cart[$j]['goodsName'];
        $goodsThums = $cart[$j]['goodsImg'];
        $totalMoney += $goodsPrice * $goodsNums;
        //$orderScore+=($cart[$i]['shopPrice']+$cart[$i]['shuxing_money'])*$cart[$i]['goods_num'];
        //$needPay+=($cart[$i]['shopPrice']+$cart[$i]['shuxing_money'])*$cart[$i]['goods_num'];

        $sql = "INSERT INTO " . $oto . "_order_goods (`orderId`,`goodsId`,`goodsNums`,`goodsPrice`,`goodsAttrId`,`goodsAttrName`,`goodsName`,`goodsThums`,`goodsGroupId`) VALUES ('$orderId','$goodsId','$goodsNums','$goodsPrice','$goodsAttrId','$goodsAttrName','$goodsName','$goodsThums','0')";
        $result = $db->query($sql); //插入order对应的order_goods表
        //file_put_contents("tsxx.txt", "\r\n".$sql."执行：".$result."\r\n", FILE_APPEND);
        //}
        $z_money += $goodsPrice * $goodsNums;
        if ($shop_info[0]['commissionCat'] == 2 || $shop_info[0]['commissionCat'] == '2') {
            $yongjin += $goodsPrice * $goodsNums * ($cart[$j]['goodsProportion'] / 100);
        }
    }
    $totalMoney = $json[$i]['yxiaoji'];
    $z_money = $json[$i]['hxiaoji'];
    //平台配送则不包邮
    if ($shop_info[0]['deliveryFreeMoney'] <= $totalMoney && $shop_info[0]['deliveryType'] != 1) {
        $ps_money = 0;
    } else {
        $ps_money = $shop_info[0]['deliveryMoney'];
    }

    if ($json[$i]['shops_psway'] == 1 || $json[$i]['shops_psway'] == '1') {
        $ps_money = 0;
    }

    $needPay = $z_money;
    if ($shop_info[0]['commissionCat'] == 1) {
        $yongjin = $needPay * ($shop_info[0]['proportion'] / 100);
    }

    $orderScore = $z_money;
    $youhui_money = $json[$i]['yxiaoji'] - $json[$i]['hxiaoji'];
    $needPay += $ps_money;

    //$needPay=intval($json[$i]['hxiaoji']);
    //$youhui_money=(intval($json[$i]['hxiaoji'])-intval($json[$i]['yxiaoji']));
    $youhui_id = $json[$i]['shops_youhui'];
    $sql = "update " . $oto . "_orders set deliverMoney='{$ps_money}',totalMoney='{$totalMoney}',orderScore='{$orderScore}',needPay='{$needPay}',couponId='{$youhui_id}',couponMoney='{$youhui_money}',commission='{$yongjin}' where orderId='{$order[0]['orderId']}'";
    $result = $db->query($sql);
    if ($result) {
        /************增加优惠券使用记录并减少未使用优惠券**************/
        $order_id = $order[0]['orderId'];
        $sql = "select * from `" . $oto . "_orders` where `orderId`='" . $order_id . "'";
        $result = $db->query($sql);
        while ($row = $result->fetch_assoc()) {
            $order_youhui_info[$i] = $row; //将取得的所有数据赋值给person_info数组
        }
        $order_youhui_id = $order_youhui_info[$i]['couponId'];
        if ($order_youhui_id != 0 && $order_youhui_id != '0') {
            $order_youhui_id = $order_youhui_info[0]['couponId'];
            $order_youhui_money = $order_youhui_info[0]['couponMoney'];
            $time = time();
            $sql = "select * from `" . $oto . "_youhui_user_link` where `user_id`='{$user_id}' and youhui_id='{$order_youhui_id}' and u_is_effect='1'";
            $result = $db->query($sql);
            while ($row = $result->fetch_assoc()) {
                $yhq_yz[] = $row; //将取得的所有数据赋值给person_info数组
            }
            if (isset($yhq_yz)) {
                if ($yhq_yz[0]['surplus'] > 1) {
                    $surplus = $yhq_yz[0]['surplus'] - 1;
                    $l_shopId = $yhq_yz[0]['shop_id'];
                    $sql = "update " . $oto . "_youhui_user_link set surplus='{$surplus}' where `user_id`='{$user_id}' and youhui_id='{$order_youhui_id}' and u_is_effect='1'";
                    $result = $db->query($sql);
                    $sql = "INSERT INTO " . $oto . "_youhui_use_record (`youhui_id`,`userId`,`shopId`,`useTime`,`orderId`,`money`) VALUES ('$order_youhui_id','$user_id','$l_shopId','$time','$order_id','$order_youhui_money')";
                    $result = $db->query($sql);
                } else {
                    $sql = "DELETE FROM `" . $oto . "_youhui_user_link` where `user_id`='{$user_id}' and youhui_id='{$order_youhui_id}' and u_is_effect='1'";
                    $result = $db->query($sql);
                    $l_shopId = $yhq_yz[0]['shop_id'];
                    $sql = "INSERT INTO " . $oto . "_youhui_use_record (`youhui_id`,`userId`,`shopId`,`useTime`,`orderId`,`money`) VALUES ('$order_youhui_id','$user_id','$l_shopId','$time','$order_id','$order_youhui_money')";
                    $result = $db->query($sql);
                }
            }
        }
        /**************************/
    }
    //file_put_contents("tsxx.txt", "\r\n".$sql."执行：".$result."\r\n", FILE_APPEND);
}
echo json_encode($data);
